package com.example.wechattakeaway.service.Impl;

import com.example.wechattakeaway.entity.SysUser;
import com.example.wechattakeaway.enums.ResultEnum;
import com.example.wechattakeaway.enums.TokenEnum;
import com.example.wechattakeaway.exception.ResultException;
import com.example.wechattakeaway.form.userform.ChangePwdForm;
import com.example.wechattakeaway.form.userform.InsertUserForm;
import com.example.wechattakeaway.form.userform.LoginForm;
import com.example.wechattakeaway.form.userform.UpdateUserForm;
import com.example.wechattakeaway.mapper.SysUserMapper;
import com.example.wechattakeaway.security.relam.UserRealm;
import com.example.wechattakeaway.service.UserService;
import com.example.wechattakeaway.token.LoginToken;
import com.example.wechattakeaway.utils.PageUtil;
import com.example.wechattakeaway.utils.PhoneCode;
import com.example.wechattakeaway.utils.ResultVOUtil;
import com.example.wechattakeaway.vo.LoginVo;
import com.example.wechattakeaway.vo.ResultVO;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.enterprise.inject.ResolutionException;
import java.util.*;

@Repository
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    SysUserMapper userMapper;

    @Override
    public ResultVO UserRegister(InsertUserForm insertUserForm) {
        SysUser sysUser = new SysUser();
        sysUser.setPassword(insertUserForm.getPassword());
        sysUser.setSex(insertUserForm.getSex());
        sysUser.setSysuserName(insertUserForm.getSysuserName());
        sysUser.setUserPhone(insertUserForm.getUserPhone());
        sysUser.setUserRole(1);

        try{
            userMapper.UserRegister(sysUser);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        return ResultVOUtil.success(sysUser);
    }

    @Override
    public ResultVO UpdateUser(UpdateUserForm updateUserForm) {
        try{
            userMapper.UpdateUser(updateUserForm);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UserChangerPwd(ChangePwdForm changePwdForm) {
        SysUser sysUser = new SysUser();
        sysUser = userMapper.SelectUserByName(changePwdForm.getSysuserName());
        if(sysUser.getSysuserName().equals("") || sysUser.getSysuserName() == null){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }
        else if(!sysUser.getPassword().equals(changePwdForm.getOldPwd())){
            throw new ResultException(ResultEnum.PASSWORD_ERROR);
        }

        try{
            userMapper.UserChangerPwd(changePwdForm.getSysuserName(),changePwdForm.getNewPwd());
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UpdateUserRole(Integer userRole, Integer sysuserId) {
        SysUser sysUser = new SysUser();
        sysUser = userMapper.SelectUserById(sysuserId);
        if(sysUser.getSysuserName().equals("") || sysUser.getSysuserName() == null){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }
        try {
            userMapper.UpdateUserRole(userRole, sysuserId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UserLogin(LoginForm loginForm) {
        log.info("现在是用户尝试登录");

        Subject subject = SecurityUtils.getSubject();  //subject对象
        String realToken = (String) subject.getSession().getId();   //获取当前session当中的token
        System.out.println(realToken);

        //下面是当前尝试登录从而创建的一个token
        LoginToken loginToken = new LoginToken(loginForm.getSysuserName(),loginForm.getPassword(), TokenEnum.USER.toString());
        try {
            subject.login(loginToken);
            //尝试登录，没报错就说明成功，注意这个loginToken集成了UsernamePasswordToken
            //这里信息传递给realm进行验证
        }catch (UnknownAccountException e){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }catch (IncorrectCredentialsException e){
            throw new ResultException(ResultEnum.PASSWORD_ERROR);
        }catch (ResultException e){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }

        SysUser userInfo = userMapper.SelectUserByName(loginForm.getSysuserName());
        LoginVo loginVo = new LoginVo(userInfo,realToken);

        return ResultVOUtil.success (loginVo);
    }

    @Override
    public SysUser getCurrentUser() {
        Subject subject = SecurityUtils.getSubject ();   //创建一个subject对象，保存到ThreadContext的resources
        try {
            Collection collection = subject.getPrincipals ().fromRealm (UserRealm.getRealmName ()); //通过realm进行验证
            Iterator iterator = collection.iterator();
            SysUser user = new SysUser ();
            while(iterator.hasNext()) {
                Object object = iterator.next ();
                user = (SysUser) object;  //迭代集合返回用户信息
            }
            if (user==null){
                throw new ResultException(ResultEnum.SERVER_ERROR);
            }
            return user;
        }catch (NullPointerException e){
            throw new ResultException(ResultEnum.USER_NOT_LOGIN);
//            return ResultVOUtil.error(ResultEnum.USER_NOT_LOGIN);
        }
    }

    @Override
    public ResultVO UserLoginOut() {
        Subject subject = SecurityUtils.getSubject ();
        try{
            subject.logout ();
        }catch (Exception e){
            throw new ResultException(ResultEnum.SERVER_ERROR);
        }
        return ResultVOUtil.success ();
    }

    @Override
    public ResultVO SelectUserById(Integer sysuserId) {
        SysUser sysUser = new SysUser();
        try{
            sysUser = userMapper.SelectUserById(sysuserId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(sysUser);
    }

    @Override
    public ResultVO SelectAllUser(Integer pageNum) {
        PageHelper.startPage(pageNum,5);

        List<SysUser> userList = new ArrayList<>();
        try{
            userList = userMapper.SelectAllUser();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap = PageUtil.getMap(userList);

        return ResultVOUtil.success(hashMap);
    }

    @Override
    public ResultVO DeleteUserById(String sysuserName) {
        try{
            userMapper.DeleteUserById(sysuserName);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO GetPhoneCode(String userPhone) {
        return PhoneCode.getPhonemsg(userPhone);
    }

    @Override
    public ResultVO CheckPhoneCode(String userPhone, String code) {
        return PhoneCode.CheckCode(userPhone, code);
    }

    @Override
    public ResultVO SelectUserByName(String sysuserName) {
        SysUser sysUser = new SysUser();
        try{
            sysUser = userMapper.SelectUserByName(sysuserName);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(sysUser);
    }

}
